package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"oss-api/app/service"
	"oss-api/library/request"
	"oss-api/library/response"
	"strconv"
)

var Resource = new(ResourceApi)

type ResourceApi struct{}

// UploadResource 上传资源
func (r *ResourceApi) UploadResource(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Fail(err.Error()))
		return
	}
	tags := c.PostForm("tags")
	cateId := c.PostForm("cate_id")
	brief := c.PostForm("brief")
	parseInt, _ := strconv.ParseInt(cateId, 10, 64)
	url, err := service.Resource.UploadFile(file, tags, parseInt, brief)
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Fail(err.Error()))
		return
	}
	c.JSON(http.StatusOK, response.Success(url))
}

// SpecifyResource 分页获取指定类型的资源
func (r *ResourceApi) SpecifyResource(c *gin.Context) {
	var param request.ResourcePageVo
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusBadRequest, response.Fail(err.Error()))
		return
	}
	data, err := service.Resource.ResourcePage(param)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.Fail(err.Error()))
		return
	}
	c.JSON(http.StatusOK, response.Success(data))
}

// DeleteResource 删除资源
func (r *ResourceApi) DeleteResource(c *gin.Context) {
	cateId := c.Query("cate_id")
	ids := c.Query("ids")
	_, err := service.Resource.DeleteResource(cateId, ids)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.Fail(err.Error()))
		return
	}
	c.JSON(http.StatusOK, response.Success("删除资源成功"))
}

// VisitState 设置访问状态
func (r *ResourceApi) VisitState(c *gin.Context) {
	idStr, flag := c.GetQuery("id")
	if !flag {
		c.JSON(http.StatusInternalServerError, response.Fail("参数丢失"))
		return
	}
	state, flag := c.GetQuery("state")
	if !flag {
		c.JSON(http.StatusInternalServerError, response.Fail("参数丢失"))
		return
	}
	id, _ := strconv.ParseInt(idStr, 10, 64)
	parseBool, _ := strconv.ParseBool(state)
	if _, err := service.Resource.SetResourcePerm(id, parseBool); err != nil {
		c.JSON(http.StatusOK, response.Fail(err.Error()))
		return
	}
	c.JSON(http.StatusOK, response.Success("设置资源访问权限成功"))

}

// GetAllTags 获取所有标签
func (r *ResourceApi) GetAllTags(c *gin.Context) {
	data, err := service.Resource.Tags()
	if err != nil {
		c.JSON(http.StatusOK, response.Fail("获取标签失败"))
		return
	}
	c.JSON(http.StatusOK, response.Success(data))
}
